import router from "@/router";
import axios from "axios";

const request = axios.create({
  baseURL: "http://geek.itheima.net/v1_0",
  timeout: 5000,
});

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
    // 向请求头中添加token字段
    const token = localStorage.getItem('token')
    if(token){
      config.headers.Authorization = `Bearer ${token}`
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    // 监听401 token失效
    if(error.response.status === 401){
      localStorage.removeItem('token')
      router.navigate('/login')
      window.location.reload()
    }
    return Promise.reject(error);
  }
);

export { request };
